import MapLayer from "./MapLayer";
import { Globals, Dir } from "./Global";	
import { adjustNumber, log_debug } from "./Utils";

const {ccclass, property} = cc._decorator;

@ccclass
export default class BaseTank extends cc.Component {
    mapLayer: MapLayer;

    blood: number;
    isEnemy: boolean;
    canMove: boolean;
    bulletCount: number;
    level: number;
    dir: Dir;
    autoMoving: boolean;
    
    constructor() {
        super();

        this.blood = 1;
        this.isEnemy = false;
        this.dir = Dir.LEFT;
        this.level = 0;
        this.canMove = false;
        this.autoMoving = false;
        this.bulletCount  = 1;
    }

    _isCollisionWithMap() {
        let node = this.node;
        let offset = Globals.TANK_SIZE / 2;
        // 判断坐标x或是坐标y是否超出地图
        if (node.x - offset < 0 || node.x + offset > Globals.MAP_WIDTH
            || node.y - offset < 0 || node.y + offset > Globals.MAP_HEIGHT) {
            return true;
        }
        return false;
    }

    _isCollisionWithBlock() {
        // 获取当前地图上所有的block
        let blocks = this.mapLayer.blocksNode.children;
        // 获取坦克自身的包围盒
        let self_rect = this.node.getBoundingBox();
        // 检查坦克和block的包围盒是否有重合
        for (let i=0; i!=blocks.length; ++i) {
            let block = blocks[i];
            if (block.name == "block_wall" || 
                block.name == "block_stone" ||
                block.name == "block_river" ||
                block.name == "camp") {
                let block_rect = block.getBoundingBox();
                if (cc.Intersection.rectRect(self_rect, block_rect)) {
                    return true;
                }
            }
        }
        return false;
    }

    _isCollisionWithTank() {
        let self_rect = this.node.getBoundingBox();
        let enemies = this.mapLayer.enemiesNode.children;
        for (const enemy of enemies) {
            let enemy_rect = enemy.getBoundingBox();
            if (enemy != this.node && cc.Intersection.rectRect(self_rect, enemy_rect)) {
                return true;
            }
        }
        for (const player of this.mapLayer.playerNode.children) {
            let player_rect = player.getBoundingBox();
            if (player != this.node && cc.Intersection.rectRect(self_rect, player_rect)) {
                return true;
            }
        }
        return false;
    }

    _isCollisionWithProp() {
        let self_rect = this.node.getBoundingBox();
        let props = this.mapLayer.propNode.children;
        for (let i=0; i!=props.length; ++i) {
            let prop = props[i];
            let prop_rect = prop.getBoundingBox();
            if (cc.Intersection.rectRect(self_rect, prop_rect)) {
                return true;
            }
        }
        return false;
    }

    // 调整位置为8的整数倍
    _adjustPosition() {
        this.node.x = adjustNumber(this.node.x);
        this.node.y = adjustNumber(this.node.y);
    }
}
